package kuzmenkov.oip.controller;

import kuzmenkov.oip.common.I18nTool;
import org.springframework.web.jsf.FacesContextUtils;

import javax.faces.context.FacesContext;
import java.util.logging.Logger;

/**
 * This class adds error handling support for backing beans
 * User: Michael Kuzmenkov
 * Date: 01.04.2009
 * Time: 17:07:37
 */
public class ErrorSupport {

    private Logger log = Logger.getLogger (ErrorSupport.class.getName());
    private String error = null;
    private I18nTool itool;

    public ErrorSupport() {
        try {
            itool = (I18nTool) FacesContextUtils.getWebApplicationContext(
                    FacesContext.getCurrentInstance()).getBean("i18nTool");
        } catch (Exception e) {
            log.severe("Bean messageSource has not been found");
            e.printStackTrace();
        }
    }

    protected I18nTool getI18nTool () {
        return itool;
    }

    public String getError() {
        String err = error;
        this.error = null;
        return err;
    }

    /**
     * Adds a error for displaying on a page
     *
     * @param e
     */
    protected void addError(Exception e) {
        if (error == null)
            error = itool.getMessage("ErrorSupport.errorMessageBeginning")+" ";
        else
            error += itool.getMessage("ErrorSupport.errorMessageMiddle")+" ";
        this.error += e.getMessage();

        e.printStackTrace();
    }

    /**
     * Whether there was some error
     *
     * @return
     */
    public boolean getIsError() {
        return error != null;
    }

}
